package cn.xclink.wechat.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.xclink.wechat.service.TokenService;
import cn.xclink.wechat.service.WxTokenService;
import cn.xclink.wechat.service.core.CoreService;
import cn.xclink.wechat.utils.SignUtil;

@RestController
@RequestMapping("wx")
public class WxCoreController {
	 @Autowired
	 private CoreService coreService;
	 @Autowired
	 private WxTokenService wxTokenService;
	 @Autowired
	 private TokenService tokenService;
	//验证是否来自微信服务器的消息
	 /**
	  * @param signature 签名
	  * @param nonce 随机数
	  * @param timestamp 时间戳
	  * @param echostr
	  * @return
	  */
	    @RequestMapping(value = "",method = RequestMethod.GET,produces = {"text/plain;charset=UTF-8"})
	    public String checkSignature(@RequestParam(value = "signature" ,required = false) String signature  ,
	                                 @RequestParam(value = "nonce",required = false) String  nonce ,
	                                 @RequestParam(value = "timestamp",required = false) String  timestamp ,
	                                 @RequestParam(value = "echostr",required = false) String  echostr) {
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
	        	System.out.println("---------------》"+SignUtil.checkSignature(signature, timestamp, nonce));
	        	System.out.println("接入成功");
	            return echostr;
	        }
	        System.out.println("接入失败");
	        return "";
	    }

	    // 调用核心业务类接收消息、处理消息跟推送消息
	    @RequestMapping(value = "",method = RequestMethod.POST)
	    public  String post(HttpServletRequest req){
	        String respMessage = coreService.processRequest(req);
	        return respMessage;

	    }
//	    获取服务器上的 AccessToken
	    @RequestMapping(value = "getAccessToken",method = RequestMethod.GET)
	    public String getAccessToken(){
	    	String accessToken = wxTokenService.getAccessToken();
	    	return accessToken;
	    }
//	    获取本地AccessToken,如果失效就去获取服务器的AccessToken
	    @RequestMapping(value = "getLocalAccessToken",method = RequestMethod.GET)
	    public String getLocalAccessToken(){
	    	String accessToken =tokenService.LocalAccessToken();
	    	return accessToken;
	    }
}
